class Solution {
public:
     
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr||root==q||root==p)return root;
        TreeNode*left=lowestCommonAncestor(root->left,p,q);
        TreeNode*right=lowestCommonAncestor(root->right,p,q);
        if(left==nullptr&&right==nullptr)return nullptr;
        else if(left==nullptr)return right;
        else if(right==nullptr)return left;
        else return root;
          
    }
};